package elitech.vietnam.weatherfashion;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import elitech.vietnam.weatherfashion.backgroundtask.GetWeatherTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.ConfirmDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.ultilities.Tracker;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;

public class SplashScreenActivity extends Activity {

	private static final int	NUMTASK								= 4;
	private int					mTask								= 0;

	public static final String	MAIN_PREF							= "elitech.vietnam.weatherfashion.MAIN_PREF";
	public static final String	EXTRA_MESSAGE						= "message";
	public static final String	PROPERTY_REG_ID						= "registration_id";
	private static final String	PROPERTY_APP_VERSION				= "appVersion";
	private final static int	PLAY_SERVICES_RESOLUTION_REQUEST	= 9000;
	private final static String	SENDER_ID							= "793977106476";
	public final static String	UNIQUE_DEVICE_ID					= "UNIQUE_DEVICE_ID";

	GoogleCloudMessaging		gcm;
	AtomicInteger				msgId								= new AtomicInteger();
	SharedPreferences			prefs;

	private ImageView			splash_imageview;
	private ValueOption			option;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.old_activity_splash_screen);

		splash_imageview = (ImageView) findViewById(R.id.splash_imageview);

		option = GlobalValue.getInstance(SplashScreenActivity.this).readOptionInfo();
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (!Utils.isNetworkEnabled(getApplicationContext())) {
			new ConfirmDialog.Builder(this).setMessage(getString(R.string.internet_connection_request)).setYesClick(new ConfirmDialog.OnYesClick() {
				@Override
				public void doClick() {
					Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
					startActivity(intent);
				}
			}).setNoClick(new ConfirmDialog.OnNoClick() {
				@Override
				public void doClick() {
					finish();
				}
			}).build().show();
			return;
		}
		if (!checkPlayServices()) {
			finish();
		}

		mTask = 0;

		splash_imageview.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_splash));
		new OneTimeStoreID().execute();
		new GetWeatherTask(this).execute();
		new SplashScreenTask().execute();
	}

	@Override
	public void onBackPressed() {
		new ConfirmDialog.Builder(this).setMessage(getString(R.string.do_you_want_to_exit_)).setYesClick(new ConfirmDialog.OnYesClick() {
			@Override
			public void doClick() {
				finish();
			}
		}).build().show();
	}

	public synchronized void finishLoading() {
		// if (loaded)
		// return;
		// // Wait GET WEATHER complete
		// while (GetWeatherTask.gettingWeather) {
		// Utils.Log("gettingGPS " + GetWeatherTask.gettingGPS +
		// " - gettingWeather " + GetWeatherTask.gettingWeather);
		// try {
		// Thread.sleep(200);
		// } catch (Exception e) {}
		// }
		// loaded = true;
		// Intent intent = new Intent(this, MainActivity.class);
		// startActivity(intent);
		// finish();
		mTask += 1;
		if (mTask == NUMTASK) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
		}
	}

	// private void startApp() {
	// new SplashScreenTask(this).execute();
	// new Handler().postDelayed(new Runnable() {
	// @Override
	// public void run() {
	// loadingCompleted();
	// }
	// }, 1000);
	// }

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.w("GCM", "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getSharedPreferences(MAIN_PREF, Context.MODE_PRIVATE);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.length() == 0) {
			Log.i("GCM", "Registration not found.");
			return "";
		}
		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i("GCM", "App version changed.");
			return "";
		}
		return registrationId;
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getSharedPreferences(MAIN_PREF, Context.MODE_PRIVATE);
		int appVersion = getAppVersion(context);
		Log.i("GCM", "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	/**
	 * Main task
	 */
	class SplashScreenTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			if (option.isAutoLogin() && !option.getUsername().equals("") && !option.getPassword().equals("")) {

				boolean b = false;
				PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
				String gcmId = getSharedPreferences(SplashScreenActivity.MAIN_PREF, Context.MODE_PRIVATE).getString(
						SplashScreenActivity.PROPERTY_REG_ID, "");
				Utils.Log("Get User Info");
				try {
					MemberDTO user = appService.logIn(option.getUsername(), option.getPassword(), Const.COUNTRY_CODE);

					b = (user != null && user.getMemberArea().equals(Const.COUNTRY_CODE) && appService.setGCMID(user.getId(), gcmId));
					if (b == false) {
						user = null;
					} else
						user.setGcmId(gcmId);
					GlobalValue.getInstance(SplashScreenActivity.this).writeUserInfo(user);
				} catch (IOException e) {
					b = false;
				}

				Utils.Log("Get User Friend List");
				if (b) {
					try {
						Utils.getFriendList(SplashScreenActivity.this);
						b = (WFApplication.getInstance().userFriends != null);
					} catch (IOException e) {
						b = false;
					}
				}
				if (!b)
					return false;
			} else {
				GlobalValue.getInstance(SplashScreenActivity.this).writeUserInfo(null);
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			new GetListNotificationTask().execute();
			finishLoading();
		}
	}

	/**
	 * Get Device ID and Google Cloud Message ID. If failed, app will exit
	 */
	class OneTimeStoreID extends AsyncTask<Integer, Integer, Boolean> {
		SharedPreferences	pref;
		String				deviceId	= null;
		String				gcmId		= "";

		@Override
		protected void onPreExecute() {
			pref = getApplicationContext().getSharedPreferences(MAIN_PREF, Context.MODE_PRIVATE);
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			deviceId = pref.getString(UNIQUE_DEVICE_ID, null);
			if (deviceId == null || deviceId.equals("")) {
				deviceId = Tracker.getDeviceID(getApplicationContext());
				pref.edit().putString(UNIQUE_DEVICE_ID, deviceId).commit();
			}

			gcmId = getRegistrationId(getApplicationContext());
			if (gcmId.equals("")) {
				try {
					Log.w("GCM", "Registering new GCM-ID");
					if (gcm == null)
						gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
					gcmId = gcm.register(SENDER_ID);
					Log.w("GCM", "New GCM-ID" + gcmId);
					storeRegistrationId(getApplicationContext(), gcmId);
					PHPSoapServiceCaller service = new PHPSoapServiceCaller();
					int res = service.newDeviceID(deviceId, gcmId);
					return (res > 0);
				} catch (IOException ex) {
					ex.printStackTrace();
					return false;
				}
			}

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (!result) {
				Log.e("Initialize", "Initialize failed! Now exitting.");
				finish();
			} else {
				Log.w("Initialize", "Initialize success.");
				finishLoading();
			}
		}
	}

	/**
	 * Get list notification
	 */
	class GetListNotificationTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				Utils.getNotificationData(SplashScreenActivity.this);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			finishLoading();
		}
	}
}
